<template>
  <div class="sku">
    <div v-if="search_visible" id="search" class="search">
      <el-form ref="form" label-width="0.5rem" :model="searchData">
        <el-row :gutter="0">
          <el-col :span="8">
            <el-form-item label="公司名称：">
              <el-input
                id="company_name"
                v-model="searchData.company_name"
                placeholder="请输入商品名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否锁单：">
              <el-select
                style="display: block"
                v-model="searchData.order_status"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option key="0" label="开启" value="1"></el-option>
                <el-option key="1" label="锁住" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <search-tool
                :search_data.sync="searchData"
                @refesh_list="getProductList"
              ></search-tool>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="sku_header_left">
      <div>
        <el-button
          type="primary"
          size="small"
          class="el-icon-circle-plus"
          @click="addShops"
          >新增商品
        </el-button>
        <el-button
          size="small"
          @click="downloadExcel"
          class="el-icon-download"
          type="primary"
          >下载模板
        </el-button>
        <el-upload
          style="display: inline-block"
          action
          accept=".xlsx, .xls"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleExcel"
        >
          <el-button size="small" class="el-icon-upload2" type="primary"
            >上传EXCEL
          </el-button>
        </el-upload>
      </div>
      <div>
        <TableTool
          :search_visible.sync="search_visible"
          @refesh_list="getProductList"
        ></TableTool>
      </div>
    </div>
    <el-table
      @expand-change="expandChange"
      :data="tableData"
      style="width: 100%"
      height="650"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      v-loading="loading"
      row-key="keyId"
      :cell-style="{ padding: '8px,0' }"
    >
      <template slot="empty">
        <img
          class="empty-img"
          src="@/assets/imgs/zanwushuju.svg"
          style="width: 64px; height: 50px"
          alt=""
        />
        <div class="noCart">暂无数据</div>
      </template>
      <el-table-column align="center" type="selection" width="100">
      </el-table-column>
      <el-table-column align="center" label="#序号" type="index" width="60">
      </el-table-column>
      <el-table-column align="" type="expand">
        <template slot-scope="props">
          <!-- <h2 class="skuCalss" style="">SKU列表</h2> -->
          <el-table
            class="childTable"
            :data="props.row.childrenData"
            v-loading="props.row.loading"
            border
            :header-cell-style="{ background: '#efefef', color: '#606266' }"
            style="width: 100%"
            :key="'abc' + props.row.keyId"
            :row-style="{ height: '0' }"
            :cell-style="{ padding: '5px' }"
          >
            <el-table-column
              prop="sku_No"
              align="center"
              show-overflow-tooltip
              label="SKU"
            >
            </el-table-column>
            <el-table-column
              prop="univalent"
              show-overflow-tooltip
              label="单价(USD)"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="weight"
              align="center"
              show-overflow-tooltip
              label="单重(KG)"
            >
            </el-table-column>
            <el-table-column
              prop="volume.V"
              align="center"
              show-overflow-tooltip
              label="体积(CM³)"
            >
            </el-table-column>
            <el-table-column
              align="center"
              property="create_time"
              label="创建时间"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{ scope.row.create_time | dateFormat }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scopeChild">
                <el-button
                  @click="editSkuClick(scopeChild.row)"
                  type="text"
                  size="small"
                  ><i class="el-icon-edit"></i> 编辑
                </el-button>
                <el-button
                  @click="delSkuClick(scopeChild.row)"
                  type="text"
                  size="small"
                  ><i class="el-icon-delete"></i> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column align="" label="商品名称" prop="product_title">
        <template slot-scope="scope">
          <div v-if="scope.row.product_title.CN" style="word-break: break-all">
            <span class="labels"> 中文品名：</span
            >{{ scope.row.product_title.CN }}
          </div>
          <div v-if="scope.row.product_title.US" style="word-break: break-all">
            <span class="labels"> 英文品名：</span
            >{{ scope.row.product_title.US }}
          </div>
          <div v-if="scope.row.product_title.KL" style="word-break: break-all">
            <span class="labels"> 韩文品名：</span
            >{{ scope.row.product_title.KL }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="" label="商品类型" prop="product_category">
        <template slot-scope="scope">
          <div
            v-if="scope.row.product_category.CN"
            style="word-break: break-all"
          >
            <span class="labels"> 中文：</span
            >{{ scope.row.product_category.CN }}
          </div>
          <div
            v-if="scope.row.product_category.US"
            style="word-break: break-all"
          >
            <span class="labels"> 英文：</span
            >{{ scope.row.product_category.US }}
          </div>
          <div
            v-if="scope.row.product_category.KL"
            style="word-break: break-all"
          >
            <span class="labels"> 韩文：</span
            >{{ scope.row.product_category.KL }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="" label="商品描述" prop="product_describe">
        <template slot-scope="scope">
          <div
            v-if="scope.row.product_describe.CN"
            style="word-break: break-all"
          >
            <span class="labels">中文描述：</span
            >{{ scope.row.product_describe.CN }}
          </div>
          <div
            v-if="scope.row.product_describe.US"
            style="word-break: break-all"
          >
            <span class="labels">英文描述：</span
            >{{ scope.row.product_describe.US }}
          </div>
          <div
            v-if="scope.row.product_describe.KL"
            style="word-break: break-all"
          >
            <span class="labels">韩文描述：</span
            >{{ scope.row.product_describe.KL }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align=""
        property="hs_code"
        label="hscode"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        align=""
        property="create_time"
        label="创建时间"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.create_time | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="skuClick(scope.row)" type="text" size="small"
            ><i class="el-icon-document-add"></i> SKU
          </el-button>
          <el-button @click="editClick(scope.row)" type="text" size="small"
            ><i class="el-icon-edit"></i> 编辑
          </el-button>
          <el-button @click="delClick(scope.row)" type="text" size="small"
            ><i class="el-icon-delete"></i> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :child-msg="pageparm" @callFather="callFather"></Pagination>
    <SkuModal
      @submit="submitClick"
      @closeForm="closeDialog"
      :dialogVisible.sync="dialogVisible"
      :editData="editData"
      :dialogTitle="dialogTitle"
    ></SkuModal>
  </div>
</template>

<script>
import SkuModal from "./components/SkuModal.vue";
import {
  addProduct,
  getProductList,
  deleteProduct,
  updateProduct,
  getUpdateInfo,
  addProductSku,
  getProductSkuList,
  deleteProductSku,
  updateProductSku,
  skuForm,
} from "@/api/comsku";
import globalMethod from "@/utils/ExcelToJson";

export default {
  components: {
    SkuModal,
  },
  data() {
    return {
      //---------------------------------------
      searchData: {},
      search_visible: true,
      //---------------------------------------
      loading: false,
      formInline: {
        page: 1,
        limit: 20,
      },
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 20,
        total: 0,
      },
      tableData: [],
      expands: [],
      dialogVisible: false,
      dialogTitle: "",
      editData: {},
    };
  },
  created() {
    this.getProductList(this.formInline);
  },
  methods: {
    //新增（编辑）(授权)提交
    submitClick(val) {
      if (val.product_id) {
        if (val.sku_No) {
          if (val.product_sku_id) {
            this.updateProductSku(val);
          } else {
            this.addProductSku(val);
          }
        } else {
          this.updateProduct(val);
        }
      } else {
        this.addProduct(val);
      }
    },
    //新增
    addShops() {
      this.editData = {
        hs_code: "",
        products: [
          {
            country_abb: "",
            product_title: "",
            product_describe: "",
            product_category: "",
          },
        ],
      };
      this.dialogTitle = "新增";
      this.dialogVisible = true;
    },
    //新增保存产品
    async addProduct(option) {
      const res = await addProduct(option);
      if (res.data.status === 200) {
        this.dialogVisible = false;
        this.getProductList(this.formInline);
        this.$message({
          type: "success",
          message: res.data.msg,
        });
      } else {
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
    //编辑保存产品
    async updateProduct(val) {
      const res = await updateProduct(val);
      if (res.data.status === 200) {
        this.dialogVisible = false;
        this.getProductList(this.formInline);
        this.$message({
          type: "success",
          message: res.data.msg,
        });
      } else {
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
    //获取列表
    async getProductList(val) {
      this.loading = true;
      try {
        const res = await getProductList(val);
        if (res.data.status === 200) {
          this.tableData = res.data.data.data.map((item, index) => {
            item.keyId = item.product_id;
            item.childrenData = []; // 添加子表格数据
            return item;
          });
          //给分页器赋值
          this.pageparm.currentPage = res.data.data.current_page;
          this.pageparm.total = res.data.data.total;
          this.pageparm.pageSize = res.data.data.per_page;
          this.loading = false;
        } else {
          this.$message.error(res.data.msg);
          this.loading = false;
        }
      } catch (error) {
        this.loading = false;
        this.$message.error("系统错误");
      }
    },
    //sku弹窗
    skuClick(row) {
      this.editData = {
        product_id: row.product_id,
        sku_No: "",
        univalent: "",
        weight: "",
        volume: {
          L: "",
          W: "",
          H: "",
        },
      };
      this.dialogTitle = "添加SKU";
      this.dialogVisible = true;
    },
    //编辑弹窗
    async editClick(row) {
      const res = await getUpdateInfo({ product_id: row.product_id });
      this.editData = res.data.data;
      this.dialogTitle = "编辑";
      this.dialogVisible = true;
    },
    //删除商品信息
    async delClick(row) {
      this.$confirm("确定操作吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteProduct({ product_id: row.product_id });
          if (res.data.status === 200) {
            this.getProductList(this.formInline);
            this.$message({
              type: "success",
              message: res.data.msg,
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.msg,
            });
          }
        })
        .catch(() => {});
    },
    //-----------------------------sku操作---------------------------------------------------------------------------------
    //新增保存SKU
    async addProductSku(val) {
      const res = await addProductSku(val);
      if (res.data.status === 200) {
        this.dialogVisible = false;
        this.getProductSkuList(val);
        this.$message({
          type: "success",
          message: res.data.msg,
        });
      } else {
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
    //获取sku列表
    async getProductSkuList(row) {
      // 通过$set属性可设置loading实现实时加载loading效果(经过测试,通过$set直接给父层数据声明子层数据时会出现报错,所以才在获取父层表格数据时声明子层表格数据)
      this.$set(row, "loading", true);
      try {
        const res = await getProductSkuList({ product_id: row.product_id });
        if (res.data.status === 200) {
          // 遍历父层表格数据
          this.tableData.forEach((temp, index) => {
            // 找到当前展开的行，把获取到的数据赋值进去
            if (temp.keyId === row.product_id) {
              this.$set(
                this.tableData[index],
                "childrenData",
                res.data.data.data
              );
            }
          });
        } else {
          this.$set(row, "loading", false);
        }
      } catch (error) {
        this.$set(row, "loading", false);
        this.$message.error("系统错误");
      }
    },
    //展开sku列表
    expandChange(row, expandedRows) {
      if (!row.children) {
        this.getProductSkuList(row);
      }
    },
    async delSkuClick(row) {
      this.$confirm("确定操作吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteProductSku({
            product_sku_id: row.product_sku_id,
          });
          if (res.data.status === 200) {
            this.getProductSkuList(row);
            this.$message({
              type: "success",
              message: res.data.msg,
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.msg,
            });
          }
        })
        .catch(() => {});
    },
    editSkuClick(row) {
      console.log(row);
      this.editData = row;
      this.dialogTitle = "修改SKU";
      this.dialogVisible = true;
    },
    //修改sku请求
    async updateProductSku(row) {
      const res = await updateProductSku(row);
      if (res.data.status === 200) {
        this.dialogVisible = false;
        this.getProductSkuList(row);
        this.$message({
          type: "success",
          message: res.data.msg,
        });
      } else {
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
    //------------------------------弹窗、分页器--------------------------------------------------------------------------------------
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
    },
    //分页插件
    callFather(parm) {
      this.formInline.page = parm.currentPage;
      this.formInline.limit = parm.pageSize;
      this.getProductList(this.formInline);
    },
    handleExcel(file) {
      let ExcelJsonData = globalMethod.ExcelToJson(file);
      ExcelJsonData.then(async (res) => {
        let validData = res.splice(1);
        const option = await skuForm({ skuValue: validData });
        console.log(option);
      });
    },
    //下载模板
    downloadExcel() {},
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-input__inner {
  height: 32px;
  line-height: 32px;
}

.sku {
  padding: 20px 10px;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.labels {
  font-size: 13px;
  color: #a9a9a9;

  &:hover {
    color: #000;
  }
}

.childTable {
  padding: 10px 10px;
}

.skuCalss {
  text-align: center;
  line-height: 52px;
  background-color: skyblue;
  color: #fff;
  font-weight: 400;
}

.el-icon-download {
  margin: 0 8px;
}

.sku_header_left {
  display: flex;
  justify-content: space-between;
  margin: 0 0 5px 0;
}
</style>
